/**
 * Express.数据持久化示例
 */
//导入Express模块
const express = require("express");
//创建Express项目
const app = express();
//Express http服务器端口
const port = 3001;

//导入Mysql数据库访问模型
const db = require("./db/11_test_db");

//获取指定ID的书籍信息
app.get("/:id",function(req,res,next){
      let bookId = parseInt(req.params.id);
      if(Number.isNaN(bookId)){
        next();
      }else{
        db.query("SELECT * FROM books WHERE id=?",[bookId]).then(result=>
            {
                console.log(result);
                res.json(result);
            }).catch(error=>{
              console.error(error);
              res.end();
            });
      }
});

//获取书籍列表
app.get("/",function(req,res,next){
      db.query("SELECT * FROM books").then(result=>
          {
              console.log(result);
              res.json(result);
          }).catch(error=>{
            console.error(error);
            res.end();
          });
});

//新增书籍
app.post("/",function(req,res,next){
    let title = "测试书籍信息" + new Date().toLocaleString();
    db.query("INSERT INTO books(title,description) VALUES(?,?)",[
        title,"作者：赵六",
    ])
    .then(result=>{
            console.log(result.insertId);
            res.json(result);
        }).catch(error=>{
          console.error(error);
          res.end();
        });
});

//更新书籍
app.put("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
      if(Number.isNaN(bookId)){
        next();
      }else{
       let title = "测试书籍信息" + new Date().toLocaleString();
       db.query("UPDATE books SET title=?,description=? WHERE id =?",[
        title,"作者：陈三",bookId
    ])
    .then(result=>{
            console.log(result.insertId);
            res.json(result);
        }).catch(error=>{
          console.error(error);
          res.end();
        });
    }
});

//删除书籍
app.delete("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
      if(Number.isNaN(bookId)){
        next();
      }else{
       db.query("DELETE FROM books WHERE id=?",[bookId])
         .then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
          console.error(error);
          res.end();
        });
    }
});
//启动Express服务
app.listen(port,function(){
    console.log(`MyApp访问地址:http://127.0.0.1:${port}`);
});

